# coding=utf-8
import re

# sub和subn
phone = "2004-959-559 # 这是一个国外电话号码"
# 替换目标字符串中的注释
pattern = "#.*"
result = re.sub(pattern, "", phone)
print(result)
# 删除非数字的字符串 \D
pattern = "\D"
result = re.sub(pattern, "", phone)
print(result)

# 调用subn
result = re.subn(pattern, "", phone)
print(result)
print("替换的结果：", result[0])
print("替换的次数：", result[1])

# compile函数的使用
s = 'first123 line'
pattern = r'\w+'
regex = re.compile(pattern)  # 匹配至少一个字母或数字
print("使用compile函数:", regex.match(s))
print("直接使用re.match:", re.match(pattern, s))

# findall 函数的使用
pattern = r'\w+'
s = 'first 1 second 2 third 3 _ $$'
o = re.findall(pattern, s)
print(o)

# finditer函数的使用
pattern = r'\w+'
s = 'first 1 second 2 third 3 _ $$'
o = re.finditer(pattern, s)
print(o)
for i in o:
    print(i.group())

# split函数的使用
pattern = r'\d+'
s = 'a 1 b 2 c 3 d'
print(re.split(pattern, s))
# maxsplit 参数限定分隔的次数，这里限定为1，也就是只分隔一次
print(re.split(pattern, s, maxsplit=1))
